//
//  HBStatusViewModel.swift
//  sinaWeibo
//
//  Created by Beans on 16/6/26.
//  Copyright © 2016年 iceWorks. All rights reserved.
//

import UIKit
import SDWebImage

class HBStatusListViewModel: NSObject {

    static let shareInstance: HBStatusListViewModel = HBStatusListViewModel()
    private override init() {
    }

    /// 微博数组
    lazy var statusList: [HBStatusCellViewModel] = [HBStatusCellViewModel]()

    /// 缓存数据的读取逻辑 -- 先读取数据库数据, 若数据库没有数据, 则从网络加载
    func loadData(since_id: Int, max_id: Int, success: (count: Int)->(), failure: ()->()) {
        // MARK: - 读取数据库中的数据
        readDBWeibo(since_id, max_id: max_id) { (array) -> () in

            // 判断有没有微博数据
            if array.count > 0 {

                // 数据转模型
                var tempArr: [HBStatusCellViewModel] = [HBStatusCellViewModel]()
                for status in array {
                    let model = HBStatusModel(dic: status)
                    tempArr.append(HBStatusCellViewModel(model: model))
                }

                // 判断, 加载更多的时候, 对数组进行拼接
                if max_id > 0 {
                    self.statusList = self.statusList + tempArr
                } else {
                    self.statusList = tempArr + self.statusList
                }

                // 数据解析之后, 进行回调以刷新数据
                success(count: -1)

            } else {
                // 没有微博数据, 加载网络
                self.netLoadData(since_id, max_id: max_id, success: success, failure: failure)
            }
        }
    }

    // 网络加载数据
    func netLoadData(since_id: Int, max_id: Int, success: (count: Int)->(), failure: ()->()) {
        /* access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。 */

        guard let access_token = HBOauthViewModel.shareInstance.access_token else {
            return
        }

        let params = ["access_token" : access_token, "since_id" : since_id, "max_id" : max_id]

        HBHTTPClient.request(.GET, URLString: "https://api.weibo.com/2/statuses/home_timeline.json", parameters: params, success: { (JSON) -> Void in

            // 字典
            guard let jsonDict = JSON as? [String: AnyObject] else {
                return
            }

            // 获取微博列表
            guard let statuesArr = jsonDict["statuses"] as? [[String:AnyObject]] else {
                return
            }

            // MARK: - 存储数据到数据库
            self.saveDBWeibo(statuesArr)

            // 遍历, 字典转模型
            let group = dispatch_group_create()
            var tempArr: [HBStatusCellViewModel] = [HBStatusCellViewModel]()    // 临时数组来接收数据
            for status in statuesArr {
                let model = HBStatusModel(dic: status)
                
                /// 如果图片数组 == 1, 下载图片 (转发微博时只能添加文本不能发图片)
                if let picURLs = model.pic_urls == nil ? model.retweeted_status?.pic_urls : model.pic_urls where picURLs.count == 1 {
//                    printLog("单张图片")

                    dispatch_group_enter(group)
                    if let urlString = picURLs.first?.model?.thumbnail_pic, let picURL = NSURL(string: urlString) {
                        // 下载图片
                        SDWebImageManager.sharedManager().downloadWithURL(picURL, options: [], progress: nil, completed: { (_, _, _, _) -> Void in
//                            printLog("单张图片下载完成")
                            dispatch_group_leave(group)
                        })
                    }
                }

                // 添加到数组
//                self.statusList.append(HBStatusCellViewModel(model: model))
                tempArr.append(HBStatusCellViewModel(model: model))
            }

            // 判断, 加载更多的时候, 对数组进行拼接
            if max_id > 0 {
                self.statusList = self.statusList + tempArr
            } else {
                self.statusList = tempArr + self.statusList
            }
            
            dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
                // // 数据解析完成后, 告诉控制器去刷新数据 (等所有单张图片下载完了, 回调)
//                success()
                success(count: tempArr.count)
            })

            }) { (error) -> Void in
                printLog(error)
                failure()
        }
    }

    // 保存微博数据
    private func saveDBWeibo(array: [[String : AnyObject]]) {

        // sql语句
        // 增加 or replace, 防止statusId相同时, 造成插入失败
        let sql = "INSERT OR REPLACE INTO T_Status (status,statusId,userId) VALUES (?,?,?);"

        // 用户id
        guard let userId = HBOauthViewModel.shareInstance.userModel?.uid else {
            return
        }

        // 一条微博
        for dict in array {
            // 存入字典前, 需要把字典转换为二进制, 再转换为String
            guard let data = try? NSJSONSerialization.dataWithJSONObject(dict, options: []) else {
                return
            }
            guard let str = String(data: data, encoding: NSUTF8StringEncoding) else {
                return
            }

            // 微博id
            if let statusId = dict["id"] as? Int {
                // 插入微博数据
                HBDBManager.sharedInstance.queue.inTransaction({ (db, rollback) -> Void in
                    if db.executeUpdate(sql, withArgumentsInArray: [str, statusId, userId]) {
                        printLog("插入成功")
                    }
                })
            }

        }
    }

    // 读取数据库数据
    func readDBWeibo(since_id: Int, max_id: Int, closure: (array : [[String : AnyObject]])->()) {
        /*
        -- 1. 查询所有微博数据, 按id进行排序
        SELECT status,statusId FROM T_Status WHERE userId = 2504312857 ORDER BY statusId DESC;

        -- 2. 指定since_id = 3993897057051602
        SELECT status,statusId FROM T_Status WHERE userId = 2504312857 AND statusId > 3993899737245900 ORDER BY statusId DESC;

        -- 3. 指定max_id
        SELECT status,statusId FROM T_Status WHERE userId = 2504312857 AND statusId < 3993899737245900 ORDER BY statusId DESC;
        */

        var sql = "SELECT status,statusId FROM T_Status WHERE userId = 2504312857 AND \n"

        if max_id > 0 {     // 上拉更多 statusId<max_id
            sql += "statusId < \(max_id) \n"
        } else {            // 下拉刷新 statusId>since_id
            sql += "statusId > \(since_id) \n"
        }
        sql += "ORDER BY statusId DESC LIMIT 20;"
        printLog(sql)

        // sql查询
        HBDBManager.sharedInstance.queue.inDatabase { (db) -> Void in
            let result = db.executeQuery(sql, withArgumentsInArray: nil)

            // 定义数组, 接收数据库读取的字典
            var temp: [[String : AnyObject]] = [[String : AnyObject]]()

            // 判断有没有下一个
            while result.next() {
                // 读取对应字段
                let statusString = result.objectForColumnName("status") as? String
                // 把字符串转换成字典 (Sting -> data -> dict)
                guard let data = statusString?.dataUsingEncoding(NSUTF8StringEncoding) else {
                    return
                }
                guard let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String : AnyObject] else {
                    return
                }
                // 添加到数组
                temp.append(dict!)
            }
//            printLog(temp)

            // 当数据拼接完成后, 回调
            closure(array: temp)
        }
    }
}
